<template>
  <div class="menu-management-container">
    <el-row :gutter="20">
      <el-col :lg="4" :md="8" :sm="24" :xl="4" :xs="24">
        <vab-card shadow="hover">
          <el-tree
            :data="data"
            :default-expanded-keys="expandDefault"
            highlight-current
            node-key="id"
            :props="defaultProps"
            @node-click="handleNodeClick"
          />
        </vab-card>
      </el-col>
      <el-col :lg="20" :md="16" :sm="24" :xl="20" :xs="24">
        <vab-card shadow="hover">
          <div class="mb20">
            <span class="color_494949 ft12 pr5">{{ translate('部门名称') }}：</span>
            <el-autocomplete
              v-model="searchInfo"
              class="inline-input mr10"
              :fetch-suggestions="querySearch"
              placeholder="选择单位"
              @select="handleSelect"
            />
            <span class="color_494949 ft12 pr5 ml10">{{ translate('用户名称') }}：</span>
            <el-input
              v-model="searchInfo1"
              class="w192 mr10"
              :placeholder="translate('请输入用户名称')"
            />
            <span class="color_494949 ft12 pr5">{{ translate('账号') }}：</span>
            <el-input
              v-model="searchInfo2"
              class="w192 mr10"
              :placeholder="translate('请输入账号')"
            />
            <span class="color_494949 ft12 pr5">{{ translate('手机') }}：</span>
            <el-input
              v-model="searchInfo3"
              class="w192 mr10"
              :placeholder="translate('请输入手机号')"
            />
            <el-button class="settingBtn ml10" type="primary" @click="seachFn()">
              {{ translate('查询') }}
            </el-button>
          </div>
          <vab-query-form>
            <vab-query-form-top-panel :span="12">
              <el-button
                v-if="MenuAuth('add')"
                :icon="Plus"
                type="primary"
                @click="handleEdit()"
                plain
              >
                {{ translate('添加') }}
              </el-button>
            </vab-query-form-top-panel>
          </vab-query-form>
          <el-table
            v-loading="listLoading"
            border
            :data="list"
            default-expand-all
            lazy
            row-key="CompanyId"
            :tree-props="{ children: 'Contact' }"
          >
            <el-table-column
              :label="translate('用户名')"
              prop="RealName"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('登录账号')"
              prop="Account"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('性别')"
              prop="Gender"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                {{
                  row.Gender == 1
                    ? translate('男')
                    : row.Gender == 2
                    ? translate('女')
                    : translate('保密')
                }}
              </template>
            </el-table-column>
            <el-table-column
              :label="translate('手机')"
              prop="Mobile"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('电话')"
              prop="Telephone"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('邮箱')"
              prop="Email"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('所属公司')"
              prop="CompanyName"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('所在部门')"
              prop="DepartmentName"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('允许登录')"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                {{ row.Enabled ? translate('是') : translate('否') }}
              </template>
            </el-table-column>
            <el-table-column
              :label="translate('登录次数')"
              prop="LogOnCount"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('说明')"
              prop="Remark"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('操作')"
              show-overflow-tooltip
              width="280"
            >
              <template #default="{ row }">
                <el-button
                  v-if="MenuAuth('edit')"
                  size="small"
                  type="primary"
                  @click="resetpasswordFn(row)"
                  plain
                >
                  {{ translate('重置密码') }}
                </el-button>
                <el-button
                  v-if="MenuAuth('edit')"
                  size="small"
                  type="primary"
                  @click="handleEdit(row)"
                  plain
                >
                  {{ translate('编辑') }}
                </el-button>
                <el-button
                  v-if="MenuAuth('delete')"
                  size="small"
                  type="danger"
                  @click="handleDelete(row)"
                  plain
                >
                  {{ translate('删除') }}
                </el-button>
              </template>
            </el-table-column>
            <template #empty>
              <!-- <el-image
                class="vab-data-empty"
                :src="require('@/assets/empty_images/data_empty.png')"
              /> -->
              <el-empty
                class="vab-data-empty"
                :description="translate('暂无数据')"
              />
            </template>
          </el-table>
          <el-pagination
            background
            :current-page="queryForm.pageNo"
            :layout="layout"
            :page-size="queryForm.pageSize"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </vab-card>
      </el-col>
    </el-row>
    <edit ref="editRef" :datalist="data" @refresh-route="refreshRoute" />
  </div>
</template>

<script>
  import { doDelete, getList, resetpassword } from '@/api/userManagement'
  import { getTree } from '@/api/companyManagement'
  import { GetPageDataVisit } from '@/api/item'
  import { Plus } from '@element-plus/icons-vue'
  import { useSettingsStore } from '@/store/modules/settings'
  import { MenuAuth } from '~/src/utils/permission'
  import { translate } from '@/i18n'
  export default defineComponent({
    name: 'UserManagementEdit',
    components: {
      Edit: defineAsyncComponent(() =>
        import('./components/UserManagementEdit')
      ),
    },
    setup() {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')
      const state = reactive({
        editRef: null,
        data: [],
        defaultProps: {
          children: 'ChildNodes',
          label: 'text',
        },
        list: [],
        WHdata: [],
        queryForm: {
          companyId: 'string',
          pageNo: 1,
          pageSize: 20,
          wheres: `[{"name":"CompanyId","value":"value","displayType":"equal"}]`,
          export: false,
        },
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        listLoading: true,
        expandDefault: [],
        searchInfo: '',
        searchInfo1: '',
        searchInfo2: '',
        searchInfo3: '',
      })
      //列表编辑
      const handleEdit = (row) => {
        if (row && row.UserId) {
          console.log(state)
          state['editRef'].showEdit(row, state)
        } else {
          if (!row) state.queryForm.userId = 0
          state['editRef'].showEdit(state.queryForm.userId, state)
        }
      }
      //页面刷新
      const settingsStore = useSettingsStore()
      const { theme } = storeToRefs(settingsStore)
      const $pub = inject('$pub')
      const refreshRoute = () => {
        $pub('reload-router-view')
      }
      //列表删除
      const handleDelete = (row) => {
        if (row.UserId) {
          $baseConfirm(translate('你确定要删除当前项吗'), null, async () => {
            const data = await doDelete({ uid: row.UserId })
            //删除列表默认回到第一页
            if (data.code == '200') {
              $baseMessage(data.message, 'success', 'vab-hey-message-success')
              fetchData()
            }
          })
        }
      }
      //列表删除
      const resetpasswordFn = (row) => {
        if (row.UserId) {
          $baseConfirm(translate('你确定重置该用户密码吗'), null, async () => {
            const data = await resetpassword({ userId: row.UserId })
            //删除列表默认回到第一页
            if (data.code == '200') {
              $baseMessage(data.message, 'success', 'vab-hey-message-success')
              fetchData()
            }
          })
        }
      }
      //菜单表格
      const fetchData = async () => {
        state.listLoading = true
        const data = await getList(state.queryForm)
        state.list = data.data.rows
        state.total = data.data.total
        state.listLoading = false
        console.log(state.list)
      }
      //树形数据点击
      const handleNodeClick = (data) => {
        //树形点击结构判断
        if (data.ChildNodes && data.ChildNodes.length > 1) {
          state.queryForm.moduleType = 'ParentId'
        } else {
          state.queryForm.moduleType = 'CompanyId'
        }
        state.queryForm.companyId = data.id
        state.queryForm.wheres = JSON.stringify([
          { name: 'CompanyId', value: data.id, displayType: 'equal' },
        ])
        fetchData()
      }
      //分页条数切换
      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      //分页切换
      const handleCurrentChange = (val) => {
        state.queryForm.pageNo = val
        fetchData()
      }
      //获取树形结构下第一个ID
      const getFirstNode = (tree) => {
        if (tree.ChildNodes.length > 0) {
          getFirstNode(tree.ChildNodes[0])
        } else {
          state.queryForm.companyId = tree.id
          state.queryForm.wheres = JSON.stringify([
            { name: 'CompanyId', value: tree.id, displayType: 'equal' },
          ])
          return
        }
      }
      const seachFn = () => {
        state.queryForm.wheres = JSON.stringify([
            { name: 'DepartmentName', value: state.searchInfo, displayType: 'like' },
            { name: 'RealName', value: state.searchInfo1, displayType: 'like' },
            { name: 'Account', value: state.searchInfo2, displayType: 'like' },
            { name: 'Mobile', value: state.searchInfo3, displayType: 'like' },
            {name:'CompanyId',value:state.queryForm.companyId,displayType: 'like'}
          ])
        console.log(state.queryForm.wheres)
        fetchData()
      }
      const WHGetPageData1 = async () => {
          const params = {
            pageNo: 1,
            pageSize: 10,
            wheres: `[{"name":"ModuleId","value":"","displayType":"equal"}]`,
            export: true,
            moduleType: 'ModuleId',
            sort: 'SortCode',
            order: 'ASC',
            search: '',
          }
          const data = await GetPageDataVisit(params)
          if (data.data.rows && data.data.rows.length > 0) {
            data.data.rows.map((item) => {
              item.value = item.FullName
            })
          }
          state.WHdata = data.data.rows
        }
      WHGetPageData1()
      //树形结构数据
      getTree().then(({ data }) => {
        const list = data.data
        state.data = JSON.parse(list)
        //默认选中第一个
        getFirstNode(state.data[0])
        state.expandDefault.push(state.queryForm.companyId)
        fetchData()
      })
      const querySearch = (queryString, cb) => {
        const restaurants = state.WHdata
        const results =
          queryString && queryString != 'null'
            ? restaurants.filter(createFilter(queryString))
            : restaurants
        console.log(results)
        // 调用 callback 返回建议列表的数据
        cb(results)
      }
  const createFilter = (queryString) => {
    return (restaurant) => {
      console.log(restaurant)
      return (
        restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      )
    }
  }
      // onMounted(() => {
      //   fetchData()
      // })

      return {
        ...toRefs(state),
        handleEdit,
        handleDelete,
        fetchData,
        handleNodeClick,
        Plus,
        handleCurrentChange,
        handleSizeChange,
        refreshRoute,
        MenuAuth,
        translate,
        resetpasswordFn,
        seachFn,
        querySearch,
        createFilter,
        WHGetPageData1,
      }
    },
  })
</script>

<style lang="scss" scoped>
  $base: '.menu-management';
  #{$base}-container {
    padding: 0 !important;
    background: $base-color-background !important;
  }
  .color_494949 {
      color: #494949;
    }
    .w192 {
      width: 192px;
    }
    .mb20 {
      margin-bottom: 20px;
    }
    .mr10 {
      margin-right: 10px;
    }
    .ml10 {
      margin-left: 10px;
    }
</style>
